﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BeerScanatronUI.ScanatronService;
using System.Reflection;

namespace BeerScanatronUI
{
    public partial class Kiosk : Form
    {
        /// <summary>
        /// Current state.  Only modify with EnterNewState method!
        /// </summary>
        StateMachine _state = StateMachine.Initialize;

        /// <summary>
        /// Max number of beers a drinker may consume in one day.
        /// </summary>
        int _beerDailyLimit;

        /// <summary>
        /// Service references.
        /// </summary>
        private IServiceProvider _sp;

        public Kiosk(IServiceProvider sp, bool isServerConnected)
        {
            _sp = sp;

            // Setup for initialization.
            _state = StateMachine.Initialize;

            InitializeComponent();
            pboxPassword.Image = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(Consts.Images.Lock));
            pboxExit.Image = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(Consts.Images.Exit));
            Bitmap bitmap;
            if (!isServerConnected)
            {
                bitmap = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(Consts.Images.NetworkFailure));
                pboxNetworkDown1.Image = bitmap;
                pboxNetworkDown2.Image = bitmap;

                FatalErrorUIInstructions = "Restart when server is ready.";
            }

            // Initialize state machine and UI.
            ProcessScanCode(null);
            lblBeverage1.Text = "(Nothing yet)";
            lblBeverage2.Text = "";
            lblBeverage3.Text = "";
            lblBeverage4.Text = "";
            lblBeverage5.Text = "";
            lblBeverage6.Text = "";
            pnlPassword.Size = new Size(pnlPassword.Size.Width, pnlPassword.Size.Height * 2);

            // Set state for all UserImage controls and associated labels.
            bitmap = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("BeerScanatronUI.Resources.female.png"));

            ((IUserImage)userImageMain).SetImageEffects(UserImage.Effects.None);            
            ((IUserImage)userImageSide1).SetUserImage(bitmap);
            lblImageSide1.Text = "";
            userImageSide1.Visible = false;

            ((IUserImage)userImageSide2).SetUserImage(bitmap);
            lblImageSide2.Text = "";
            userImageSide2.Visible = false;

            if (isServerConnected)
            {
                // Server up.  Continue setup.
                _beerDailyLimit = GetService<IServer>().GetBeverageDailyLimit();
                timerSalesTally.Enabled = true;
            }
            else
            {
                // Server down.  Disable screen.
                this.pboxExit.Enabled = true;
                foreach (Control control in this.tableLayoutPanel1.Controls)
                {
                    if (control != pnlPassword && control != panel2)
                    {
                        control.Enabled = false;
                    }
                }
                txtBarcode.Visible = false;
                label3.Visible = false;
                lblBeverage1.Visible = false;
            }
        }

        /// <summary>
        /// Get service helper.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private T GetService<T>()
        {
            Type t = typeof(T);
            return (T)_sp.GetService(t);
        }

        private void pboxExit_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you wish to exit this program?", "Confirm exit",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (result == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Cancel;
            }
        }

        /// <summary>
        /// If user presses ESCAPE, clear the input text box.
        /// If user presses RETURN, they have entered a barcode manually in the text box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Kiosk_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                // ESCAPE: Clear text box.
                txtBarcode.Text = "";
            }
            else if (e.KeyCode == Keys.Return)
            {
                // Accept manual user entry into text box as a complete key code without the trailing "a"
                //  as the scanner would do.
                ScanCode code = new ScanCode(txtBarcode.Text);
                txtBarcode.Text = "";

                // Process text.
                ProcessScanCode(code);
            }
        }

        /// <summary>
        /// We are waiting for a scanner code or code entered from keyboard.  If there is a lower-case A,
        /// then this is the terminating delimiter for scanner entered data.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBarcode_TextChanged(object sender, EventArgs e)
        {
            if (txtBarcode.Text.EndsWith("a"))
            {
                // Got lower-case "a" - scanner has completed input.
                ScanCode code = new ScanCode(txtBarcode.Text);
                txtBarcode.Text = "";

                // Process text.
                ProcessScanCode(code);
            }
        }

        /// <summary>
        /// Code is kind of ugly.  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerSalesTally_Tick(object sender, EventArgs e)
        {
            // Clean out old data.
            lblBeverage1.Text = "";
            lblBeverage2.Text = "";
            lblBeverage3.Text = "";
            lblBeverage4.Text = "";
            lblBeverage5.Text = "";
            lblBeverage6.Text = "";
            Label[] labelCollection = new Label[] { lblBeverage1, lblBeverage2, lblBeverage3, lblBeverage4, lblBeverage5, lblBeverage6 };

            IServer server = GetService<IServer>();
            IList<KeyValuePair<Beer, int>> results = server.GetBeverageSalesToday();
            if (results != null && results.Count > 0)
            {
                var sortedResults = results.OrderByDescending(t => t.Value);
                IEnumerator<KeyValuePair<Beer, int>> list = sortedResults.GetEnumerator();
                foreach (var item in labelCollection)
                {
                    if (!list.MoveNext())
                    {
                        // End of list.
                        break;
                    }

                    String s = String.Format("{0} - {1}\n", list.Current.Key.Name, list.Current.Value);
                    item.Text = s;
                }
            }
        }

        /// <summary>
        /// Allow user to enter AdminUI screen with password.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pboxPassword_Click(object sender, EventArgs e)
        {
            using (EnterTextDialog dlg = new EnterTextDialog(true))
            {
                dlg.Text = "Password required";
                dlg.Prompt = "Enter password.";
                bool pwValid = false;
                
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    // Test password.
                    if (!String.IsNullOrWhiteSpace(dlg.Prompt) 
                        && dlg.Response == Properties.Settings.Default.KioskPassword)
                    {
                        this.DialogResult = DialogResult.OK;
                        pwValid = true;
                    }
                }

                if (!pwValid)
                {
                    MessageBox.Show("Incorrect password entered.", "Password invalid",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Make sure text box retains focus so scanner input is always read.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBarcode_Leave(object sender, EventArgs e)
        {
            Debug.WriteLine("Leave");
            txtBarcode.Focus();
        }
    }
}
